package com.panopset.db;

import java.io.StringWriter;

/**
 * DataField for TableDescription field definition.
 * @author Karl Dinwiddie
 */
public abstract class DataField {

    /**
     * @param name
     *            Name of the field. Should be simple, lower case and contain no
     *            special characters.
     */
    public DataField(final String name) {
        nm = name;
    }

    /**
     * @return Name of this field.
     */
    public final String getName() {
        return nm;
    }

    /**
     * @return Field attributes.
     */
    public abstract String getAttributes();

    /**
     * Defaults to empty String.
     * @return Additional attributes, if overridden.
     */
    public String getAdditionalAttributes() {
        return "";
    }

    /**
     * @return True if there are additional attributes for this field.
     */
    public final boolean hasAdditionalAttributes() {
        return getAdditionalAttributes() != null
                && getAdditionalAttributes().trim().length() > 0;
    }

    /**
     * @return True if this is a primary key field.
     */
    protected final boolean isPrimaryKey() {
        return isPrimaryKey;
    }

    /**
     * @return True if this field is indexed.
     */
    public final boolean isIndexed() {
        return isIndexed;
    }

    /**
     * Set as primary key.
     */
    protected final void setPrimaryKey() {
        isPrimaryKey = true;
    }

    /**
     * Make this an indexed field.
     * @return this.
     */
    public final DataField setIndexed() {
        isIndexed = true;
        return this;
    }

    /**
     * @return True if this is a unique field.
     */
    public final boolean isUnique() {
        return isUnique;
    }

    /**
     * Make this a unique field.
     * @return this.
     */
    public final DataField setUnique() {
        isUnique = true;
        return this;
    }

    /**
     * Is indexed.
     */
    private Boolean isIndexed = false;

    /**
     * Is unique.
     */
    private Boolean isUnique = false;

    /**
     * Is primary key.
     */
    private Boolean isPrimaryKey = false;

    /**
     * Name.
     */
    private final String nm;

    /**
     * Create table command.
     */
    private String tblCmd;

    /**
     * @return Create table command.
     */
    public final String getCreateTableCmd() {
        if (tblCmd == null) {
            StringWriter sw = new StringWriter();
            sw.append(getName());
            sw.append(" ");
            sw.append(getAttributes());
            tblCmd = sw.toString();
        }
        return tblCmd;
    }
}
